const express = require("express");
const app = express();
const path = require("path");
const jwt = require("./jwt/jwt.js");
const bodyParser = require("body-parser");

// 导入数据库
require("./config/DB.config.js");

// 导入对应的路由
const UserRouter = require("./routes/user/UserRouter.js");
const RoleRouter = require("./routes/role/RoleRouter.js");
const DepartRouter = require("./routes/depart/DepartRouter.js");
const WordRouter = require("./routes/word/WordRouter.js");

const PORT = 8888;
const HOST = "http://localhost";
const HOSTNAME = `${HOST}:${PORT}`;

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

// 解析请求体中的JSON对象
app.use(express.json());

// app.use(express.urlencoded({ extended: false }));

// 解析Form表单中的数据，转换URL编码
app.use(
  bodyParser.urlencoded({
    extended: false,
    limit: "1024mb",
  })
);

app.use(express.static(`./`));
// app.use(express.static(path.join(__dirname, "public")));

/* 
  登录校验
*/
app.use(function (req, res, next) {
  if (req.path === "/user/login") {
    // 登录页不需要鉴权直接放行
    next();
    return;
  }
  let token = req.headers.authorization;
  let user = jwt.verify(token); //md5pswsolt,username
  // token不存在或token失效，最终经过解密都是错误的
  if (!user) {
    res.send({
      code: -1,
      message: "token失效！",
    });
    return;
  }
  req.$TOKEN = user; //挂载用户信息
  next();
});

// 匹配用户相关的路由
app.use(UserRouter);
app.use(RoleRouter);
app.use(DepartRouter);
app.use(WordRouter);

app.use((req, res) => {
  res.status(404);
  res.send("NOT FOUND!");
});

app.listen(PORT, () => {
  console.log(
    `THE WEB SERVICE IS CREATED SUCCESSFULLY AND IS LISTENING TO THE PORT：${PORT}，YOU CAN VISIT：${HOSTNAME}`
  );
});
